package com.wiseasy.smartpos.cashierdemo.util;

import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.graphics.PointF;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

public class NfcLogoLocationUtils {

    public static void moveToWord(final View view, final float targetX, final float targetY) {

        final float x = view.getX();
        final float y = view.getY();

        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setDuration(600);
        valueAnimator.setObjectValues(new PointF(x, y));

        valueAnimator.setInterpolator(new DecelerateInterpolator());


        final boolean flagX = ((x - targetX) > 0);
        final boolean flagY = ((y - targetY) > 0);


        valueAnimator.setEvaluator(new TypeEvaluator<PointF>() {

            @Override
            public PointF evaluate(float fraction, PointF startValue,
                                   PointF endValue) {
                PointF point = new PointF();
                float fractionNeed = 1 - fraction;

                if (flagX) {
                    float vX = x - targetX;
                    point.x = vX * fractionNeed + targetX;
                } else {
                    float vX = targetX - x;
                    point.x = x + vX * fraction;
                }

                if (flagY) {
                    float vY = y - targetY;
                    point.y = vY * fractionNeed + targetY;
                } else {
                    float vY = targetY - y;
                    point.y = y + vY * fraction;
                }
                return point;

            }
        });
        valueAnimator.start();
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                PointF point = (PointF) animation.getAnimatedValue();
                float vX = point.x;
                float vY = point.y;

                if (flagX) {
                    if (vX <= x && vX >= targetX) {
                        view.setX(vX);
                    }
                } else {
                    if (vX >= x && vX <= targetX) {
                        view.setX(vX);
                    }
                }

                if (flagY) {
                    if (vY <= y && vY >= targetY) {
                        view.setY(vY);
                    }
                } else {
                    if (vY >= y && vY <= targetY) {
                        view.setY(vY);
                    }
                }
            }
        });
    }
}
